<template>
  <div>
    <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
      <el-form-item label="账号" prop="username">
        <el-input v-model.number="ruleForm.username"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input type="password" v-model="ruleForm.password" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="checkPass">
        <el-input type="password" v-model="checkPass" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="角色">
        <el-radio-group v-model="ruleForm.role">
          <el-radio label="管理员"></el-radio>
          <el-radio label="普通用户"></el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>

</template>

<script>
export default {
  data() {
    var checkUsername = (rule, value, callback) => {
      if(this.ruleForm.username.length<6){
        callback(new Error('账号长度不足6位！'));
      }else{
        this.axios.get("/user/checkUsername?username="+this.ruleForm.username).then(res=>{
          if(res.data=='200'){
            callback(new Error('账号已存在，请重新输入！'));
          }else{
            callback();
          }
        })
      }
    };
    var validatePass = (rule, value, callback) => {
      if (this.ruleForm.password.length==0) {
        callback(new Error('请输入密码'));
      } else {
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (this.checkPass.length==0) {
        callback(new Error('请再次输入密码'));
      } else if (this.checkPass !== this.ruleForm.password) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    return {
      ruleForm: {
        password: '',
        username:''
      },
      checkPass:'',
      rules: {
        // validator 校验方法
        // trigger 触发器
        password: [
          { validator: validatePass, trigger: 'blur' }
        ],
        checkPass: [
          { validator: validatePass2, trigger: 'blur' }
        ],
        username: [
          { validator: checkUsername, trigger: 'blur' }
        ]
      }
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.axios.post("/user/register",this.ruleForm).then(res=>{
            if(res.data =='200'){
              this.$router.push("/");
            }
          });
        } else {
          this.$message.error("对不起，请确认你的信息是否正确！");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  }
}
</script>


<style>

</style>